package manage.sys.service.impl;

import java.util.List;

import javax.annotation.PostConstruct;

import org.quartz.CronTrigger;
import org.quartz.Scheduler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import luxing.common.service.impl.CommonServiceImpl;
import luxing.util.ScheduleUtil;
import manage.sys.entity.ScheduleJob;
import manage.sys.service.ScheduleJobService;

/**
 * 
 * @author zzc
 *
 */
@Service("scheduleJobService")
@Transactional
public class ScheduleJobServiceImpl extends CommonServiceImpl implements ScheduleJobService {

	@Autowired
	private Scheduler scheduler;

	@PostConstruct
	public void init() {
		String sql = "select * from manage_schedule_job";
		List<ScheduleJob> scheduleJobList = listBySql(sql, ScheduleJob.class, null);
		for (ScheduleJob scheduleJob : scheduleJobList) {
			CronTrigger cronTrigger = ScheduleUtil.getCronTrigger(scheduler, scheduleJob.getId());
			// 如果不存在，则创建
			if (cronTrigger == null) {
				ScheduleUtil.createScheduleJob(scheduler, scheduleJob);
			} else {
				ScheduleUtil.updateScheduleJob(scheduler, scheduleJob);
			}
		}
	}

	public void save(ScheduleJob scheduleJob) {
		super.save(scheduleJob);
		ScheduleUtil.createScheduleJob(scheduler, scheduleJob);
	}

	public void update(ScheduleJob scheduleJob) {
		ScheduleUtil.updateScheduleJob(scheduler, scheduleJob);
		saveOrUpdate(scheduleJob);
	}

	public void delete(ScheduleJob scheduleJob) {
		ScheduleUtil.deleteScheduleJob(scheduler, scheduleJob.getId());
		super.delete(scheduleJob);
	}

	public void run(ScheduleJob scheduleJob) {
		ScheduleUtil.run(scheduler, scheduleJob);
	}

	public void pause(ScheduleJob scheduleJob) {
		ScheduleUtil.pauseJob(scheduler, scheduleJob.getId());
		scheduleJob.setStatus(ScheduleJob.STATUS_PAUSE);
		saveOrUpdate(scheduleJob);
	}

	public void resume(ScheduleJob scheduleJob) {
		ScheduleUtil.resumeJob(scheduler, scheduleJob.getId());
		scheduleJob.setStatus(ScheduleJob.STATUS_NORMAL);
		saveOrUpdate(scheduleJob);
	}

}
